package com.Policing.Shift;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Receive.add_recipient;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Receive.add_admin;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.CanniBalize.Shift_site;
import com.Policing.bean.Input_item;

import com.senter.iot.support.openapi.uhf.UhfD2;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Allot_Add extends Activity implements OnDismissListener {
    private ImageView imageView;
    private LinearLayout suspension,admin_ly,allot_recipient;
    private Button up_bt,scan_img,rfid_bt;//上传数据，扫码
    private List<String> date = new ArrayList<>();
    private List<Input_item> data = new ArrayList<>();//扫码
    private List<String> assetId = new ArrayList<>();//资产id
    private EditText allot_remark,et_num;//备注
    private ListView lv_list;
    private String id;
    private String admin_id,name;
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private Allot_Add content;
    private List<String> rfid_data = new ArrayList<>();

    private Handler handler = new Handler();
    private String site_id="";
    private String url_up ="http://"+ Ip_Set.IP+"/api/transferAdd";//上传
    private String url ="http://"+ Ip_Set.IP+"/api/assetScanTransferQuery";//获取资产信息url
    private String fold_unit_id="",call_department_id="",allot_recipient_id="";//转移单位，转移部门，接收人id
    private TextView fold_section,select_department,site_tv,admin_tv,title_text,recipient;//转移单位，转移部门，接收人name
    private LinearLayout fold_unit,call_department,site_ll;//转移单位转移部门，接收人
    private boolean state;
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(Allot_Add.this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    private boolean isrfid=true;
    private boolean stop_rfid =true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.allot_add);
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        name = mm.getString("name","");
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        content = this;
        admin_id = id;
        date.clear();
        lv_data.clear();
        inview();
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i=0;i<data.size();i++){
                    if (et_num.getText().toString().trim().equals(data.get(i).getCode_number())){
                        Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("")&&et_num.length()>9){
                    if (!lv_data.contains(et_num.getText().toString().trim())){
                        post(et_num.getText().toString().trim(),"");
                    }else {
                        Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(content,"错误的格式",Toast.LENGTH_SHORT).show();
                }
            }
        });
        admin_ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(content, add_admin.class);
                startActivityForResult(intent,7);
            }
        });
        site_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(content, Shift_site.class);
                startActivityForResult(intent,4);
            }
        });
        fold_unit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recipient.setText("");
                allot_recipient_id="";
                call_department_id ="";
                select_department.setText("");
                Intent dept = new Intent(content, Allot_unit.class);
                startActivityForResult(dept, 1);
            }
        });
        call_department.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!fold_section.getText().toString().equals("")){
                    recipient.setText("");
                    allot_recipient_id="";
                    Intent intent = new Intent(content, Allot_department.class);
                    intent.putExtra("department_id", fold_unit_id);
                    startActivityForResult(intent,2);
                }
            }
        });
        allot_recipient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!select_department.getText().toString().equals("")) {
                    Intent intent = new Intent(Allot_Add.this, add_recipient.class);
                    intent.putExtra("department_id", call_department_id);
                    startActivityForResult(intent,3);

                }
            }
        });
        up_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data.size()<=0){
                    Toast.makeText(content,"请扫码需要转移的资产",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (fold_unit_id.equals("")||call_department_id.equals("")||recipient.getText().toString().trim().equals("")){
                    Toast.makeText(content,"请完善数据",Toast.LENGTH_SHORT).show();
                    return;
                }
                new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            assetId.clear();
                            for (int i =0;i<data.size();i++){
                                assetId.add(data.get(i).getCode_number());
                            }
                            upload();
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(content).show();
            }
        });
        rfid_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isrfid==true){
                        if (UhfD2.getInstance().init() == true){
                            UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                        }
                        isrfid = false;
                    }

                }catch (Exception E){
                    Toast.makeText(content,"没有RFID模块",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (stop_rfid){
                    stop_rfid=false;
                    start_read();
                    rfid_bt.setText("停止读取");
                }else {
                    stop_rfid=true;
                    state =false;
                    rfid_bt.setText("开启RFID");
                }

            }
        });
    }
    private void inview() {
        et_num = (EditText) findViewById(R.id.et_num);
        rfid_bt  = (Button) findViewById(R.id.Rfid);
        allot_recipient = (LinearLayout) findViewById(R.id.allot_recipient);
        title_text  = (TextView) findViewById(R.id.title_text);
        title_text.setText("添加转移单");
        admin_ly = (LinearLayout)findViewById(R.id.admin_ly);
        admin_tv = (TextView)findViewById(R.id.admin_tv);
        admin_tv.setText(name);
        site_tv = (TextView) findViewById(R.id.site_tv);
        site_ll = (LinearLayout)findViewById(R.id.site_ll);
        suspension = (LinearLayout)findViewById(R.id.suspension);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        scan_img = (Button) findViewById(R.id.scan_img);
        call_department = (LinearLayout) findViewById(R.id.call_department);
        fold_unit = (LinearLayout) findViewById(R.id.fold_unit);
        recipient = (TextView) findViewById(R.id.recipient);
        fold_section = (TextView) findViewById(R.id.fold_section);
        select_department = (TextView) findViewById(R.id.select_department);
        up_bt = (Button)findViewById(R.id.allot_upload);
        allot_remark = (EditText) findViewById(R.id.allot_remark);
        imageView = (ImageView) findViewById(R.id.fh);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int i, long id) {
                new AlertView(" 提示！", "是否删除", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){

                            for (int j=0;j<lv_data.size();j++){
                                if (lv_data.get(j).equals(data.get(i).getCode_number())){
                                    lv_data.remove(j);
                                }
                            }
                            data.remove(i);
                            Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                            lv_list.setAdapter(adapter_item);
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(content).show();
            }
        });
    }
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onDismiss(Object o) {

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            fold_unit_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            fold_section.setText(name);

        }
        if (requestCode==2&&resultCode==2){
            call_department_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            select_department.setText(name);
        }
        if (requestCode==3&&resultCode==3){
            allot_recipient_id = data.getExtras().getString("recipient_id");
            String name = data.getExtras().getString("recipient_name");
            recipient.setText(name);
        }
        if (requestCode==4&&resultCode==3){
            site_tv.setText(data.getExtras().getString("site_name"));
            site_id = data.getExtras().getString("site_id");
        }
        if (requestCode==7&&resultCode==7){
            admin_tv.setText(data.getExtras().getString("admin_name"));
            admin_id = data.getExtras().getString("admin_id");
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (!lv_data.contains(scanResult)){

                post(scanResult,"");
            }else Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
        }
    }

    private void post(final String assetNumber, final String rfid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber",assetNumber)
                .add("rfid",rfid);
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("123123", responseData);
                                    Bitmap bitmap =null;
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("state").equals("1")){
                                        lv_data.add(assetNumber);
                                        JSONObject json = jsonObject.getJSONObject("asset");
                                        String assetName = json.getString("assetName");
                                        String deptId = json.getString("deptId");
                                        String assetNumber = json.getString("assetNumber");
                                        String userId = json.getString("userId");
                                        String model = json.getString("model");
                                        String type = json.getString("type");
                                        if (json.getString("image").equals("")){
                                            @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                            bitmap = BitmapFactory.decodeStream(is);
                                        }else {
                                            byte [] input = Base64.decode(json.getString("image"), Base64.DEFAULT);
                                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                        }
                                        Collections.reverse(data);
                                        data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));
                                        Collections.reverse(data);
                                        Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                                        lv_list.setAdapter(adapter_item);
                                        Toast.makeText(content,"添加成功",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("0")){
                                        Toast.makeText(content,"失败",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("2")){
                                        Toast.makeText(content,"资产不存在",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("3")){
                                        Toast.makeText(content,"当前资产不可转移",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });

                    }
                });

            }
        }).start();
    }
    private void upload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("inunit",fold_unit_id)
                        .add("userId",id)
                        .add("admin",admin_id)
                        .add("place",site_id)
                        .add("assetNumbers", String.valueOf(assetId))
                        .add("indept",call_department_id)
                        .add("inuser",allot_recipient_id)
                        .add("remark",allot_remark.getText().toString()); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url_up)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("123123", responseData);
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("state").equals("1")){
                                        finish();
                                        Toast.makeText(content,"提交成功",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("0")){
                                        Toast.makeText(content,"提交失败",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();
    }



    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                for (int i = 0; i<data.size();i++){
                    if (DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4).equals(data.get(i).getRfid())){
                        return;
                    }
                }
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    final String rfid = DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            post("",rfid);
                        }
                    },300);
                    trigTagAccompainiment();//播放声音
                }
            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
}
